package com.wthink.card.Thread;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.wthink.card.ShdThread;
import com.wthink.card.models.Utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.security.InvalidParameterException;

public class SerialFrameProcThread extends ShdThread {

	private static final String THIS_FILE = "SerialFrameProcThread";
	private static SerialFrameProcThread _instance;
	private static SerialPort vcaSerialPort;
	private static InputStream vcaIS;
	private static OutputStream vcaOS;
	//private static int baude = 19200;
	private static int baude = 115200;

	public static final int SCREEN_WORK_MODE_NORMAL = 0;
	public static final int SCREEN_WORK_MODE_UPDATE = 1;
	private static int mode = SCREEN_WORK_MODE_NORMAL;

	public SerialFrameProcThread(Context ctx, Handler h){
		super(ctx, SerialFrameProcThread.THIS_FILE, h);
	}

	public SerialFrameProcThread(Context ctx){
		super(ctx, SerialFrameProcThread.THIS_FILE);
	}

	public static synchronized SerialFrameProcThread getInstance(Context ctx, Handler h) {
		if(_instance == null) {
			_instance = new SerialFrameProcThread(ctx, h);
		}
		return _instance;
	}

	public static synchronized SerialFrameProcThread getInstance(Context ctx) {
		if(_instance == null) {
			_instance = new SerialFrameProcThread(ctx);
		}
		return _instance;
	}

	public static synchronized void setInstance(Context ctx) {
		if(_instance != null) {
			_instance = null;
		}
	}

	public static void SetSerialBaud(int val){
		baude = val;
	}

	public static void SetScreenWorkMode(int val){
		mode = val;
	}
	public static int GetScreenWorkMode(){
		return mode;
	}

	public int initSerialPort() throws SecurityException, IOException, InvalidParameterException {
		try {
			if (vcaSerialPort == null) {
				/* Open the serial port */
				vcaSerialPort = new SerialPort(new File("/dev/ttyS0"), baude, 0);
				//屏上执行 10.0.0.2
				//pppd nodetach noauth noipdefault mtu 500  idle 300 local /dev/ttyS0 115200 10.0.0.1:10.0.0.2
			}
			if(vcaOS == null) {
				vcaOS = vcaSerialPort.getOutputStream();
			}
			if(vcaIS == null) {
				vcaIS = vcaSerialPort.getInputStream();
			}
		} catch (SecurityException e) {
			e.printStackTrace();
			return ER_PERMISSION_DENY;
		}
		catch (IOException e) {
			e.printStackTrace();
			return ER_SERIAL_UNKNOWN;
		}
		catch (InvalidParameterException e) {
			e.printStackTrace();
			return ER_SERIAL_PARA;
		}
		return 0;
	}

	public synchronized void closeSerialPort() {
		if(vcaIS != null){
			try {
				vcaIS.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			vcaIS = null;
		}

		if(vcaOS != null){
			try {
				vcaOS.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			vcaOS = null;
		}
		if (vcaSerialPort != null) {
			vcaSerialPort.close();
			vcaSerialPort = null;
		}
	}

	public synchronized int sendData(byte[] data,int dataLen){

		if(vcaOS == null){
			return ER_SYSTEM_EXCEPTION;
		}

		try {
			vcaOS.write(data,0,dataLen);
		} catch (IOException e) {
			// TODO Auto-generated catch blocki
			e.printStackTrace();
			return ER_SEND_FAILE;
		}


		String s1 = Utils.Bytes2HexString(data);

		Log.d("senddatas1", s1);


		String	strRead = null;
		try {
			strRead = new String(data,"GB2312");
			Log.d("senddata", strRead);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public int SendToMainBoardNormalFrm(int type, byte[] data, int datalen) {
		ByteBuffer out = ByteBuffer.allocate(BUNDLE_HEARDER_LEN + BUNDLE_TAIL_LEN + datalen);
		packMainBoardNormalFrm(type, data, datalen, out);
		return sendData(out.array(), out.position());
	}

	public int SendToMainboardOriFrm(byte[] data, int datalen){
		return sendData(data, datalen);
	}

	public void CloseOpenSerialPort(){
		try {
			Log.e(THIS_FILE, "CloseOpenSerial");
			closeSerialPort();
			initSerialPort();
		} catch (InvalidParameterException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			int rc;
			int rc2;
			Log.d("执行了","执行了");
		/*	if((vcaLastError = initSerialPort()) < 0) {
				informUIWhenFinally = true;
				return;
			}*/
			if(mode == SCREEN_WORK_MODE_NORMAL){
				while(!isInterrupted()) {
					for(int i = 0; i< 20; i++){
						rc2 = processShdFrameBundle();
						if(rc2 < 0 && rc2 != ER_WRONG_FRAME){
							vcaLastError = rc2;
							informUIWhenFinally = true;
							break;
						}
						/*rc = readAndParseShdFrame(vcaIS);
						if(rc == NR_READY_FOR_PROCESS){ // process  new shd frame bundle
							rc2 = processShdFrameBundle();
							if(rc2 < 0 && rc2 != ER_WRONG_FRAME){
								vcaLastError = rc2;
								informUIWhenFinally = true;
								break;
							}
							//sendMsgToHandler(AlbumsActivity.UI_UPDATE);
						}else if(rc <= 0 && rc != ER_WRONG_FRAME){ // error occured or socket closed by server....
							vcaLastError = rc;
							informUIWhenFinally = true;
							break;
						}*/
					}
					//Thread.sleep(20);
					Thread.sleep(Utils.OS_TICKS_PER_SEC/5);
					// continue,   we need read more
				}
			}
		} catch(InterruptedException e) {
			e.printStackTrace();
		} catch(SecurityException e){
			e.printStackTrace();
		}
		/*catch(IOException e){
			e.printStackTrace();
		}*/
		catch(InvalidParameterException e){
			e.printStackTrace();
		} finally {
			closeSerialPort();
			if(informUIWhenFinally){
				;
			}
		}
	}
}
